package com.atguigu.gmall.order.pay.controller;


import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.common.constant.RabbitConstant;
import com.atguigu.gmall.common.util.JsonUtils;
import com.atguigu.gmall.order.pay.config.PayTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 接受支付宝异步通知的
 */
@Slf4j
@RequestMapping("/alipay")
@RestController
public class AlipayNotifyController {

    @Autowired
    PayTemplate payTemplate;
    //api/order/notify/success

    @Autowired
    RabbitTemplate rabbitTemplate;

    //支付宝异步通知
    @RequestMapping("/notify/success")
    public String orderPayedSuccessAliNotify(@RequestParam Map<String,String> params){
        try {

            boolean b = payTemplate.checkSgin(params);
            if(b){
                System.out.println("支付宝异步通知，成功抵达：：：："+params);
                //修改订单状态。给MQ发送哪些订单支付成功的消息；
                String jsonStr = JsonUtils.parseObjectToJsonStr(params);
                rabbitTemplate.convertAndSend(RabbitConstant.ORDER_EVENT_EXCHANGE,RabbitConstant.ORDER_PAYED_RK,jsonStr);
            }else {
                System.out.println("有黑客模拟支付宝调用我："+params);
            }
        } catch (AlipayApiException e) {
            log.error("验签失败：{}",e);
        }

        //给支付宝响应success，支付宝就不会再发通知了。
        return "success";
    }
}
